#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 疯狂导包
import sys
import time
import math
import os
import socket
import fcntl
import struct

from PIL import Image,ImageDraw,ImageFont

import smbus
#from lib.SSD1306 import *
from lib.FAN import *
from lib.SYSTEMP import *
from lib.MQTT import *
from lib.Battery import *
from lib.ConfigJson import *

# 创建部分实例
FAN = FAN() # 一个风扇
SYSTEMP = SYSTEMP() # 一个CPU温感

Battery = Battery() # 一个电池模组
Config = ConfigJson('./config.json') # 一个配置文件

#OLED=SSD1306()
#OLED.Init()
#OLED.ClearBlack()

URL = Config.get('network.MQTT-Server.URL')
PORT = Config.get('network.MQTT-Server.port')
KEEPALIVE = Config.get('network.MQTT-Server.keepalive')

MQTT=MQTT(URL, PORT, KEEPALIVE) # 创建MQTT链接

#dir_path = os.path.dirname(os.path.abspath(__file__))
#font = ImageFont.truetype(dir_path+'/fonts/Courier_New.ttf',14)

stopCoolTemp = Config.get('hardware.fan.stopTemp') # 读取开始冷却温度
startCoolTemp = Config.get('hardware.fan.startTemp') # 读取关闭冷却温度

MQTT.subscribe('/ThickPad/FAN/Mode') # 订阅风扇模式频道

try:
    while True:
        systemp = SYSTEMP.GET_Temp() # 获取传感器温度
        if (MQTT.getFromSub('/ThickPad/FAN/Mode') == 'true'): # 判断当前上位机设置的模式
            if (systemp >= startCoolTemp):
                FAN.FAN_ON()
            elif (systemp <= stopCoolTemp):
                FAN.FAN_OFF()

        MQTT.publish('/ThickPad/FAN/State', FAN.FAN_STATE, 2, False) # 将风扇状态上报
        print(str(SYSTEMP.GET_Temp()) + '\t' + str(FAN.FAN_STATE) + '\t' + str(MQTT.getFromSub('/ThickPad/FAN/Mode'))) # 本地调试信息
        time.sleep(1)
except KeyboardInterrupt:
    print('Program Terminated!')


